﻿/*
Copyright (c) 2010 Lance Ward
This software is licensed under the MIT license, except where otherwise noted.
For complete license details, refer to license.txt
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ADNLib;

namespace ADNActions
{
	public static class Group
	{
		public static void GroupSelected(List<XObject> xobjects, List<XObject> selection)
		{
			if (selection != null && selection.Count > 1 && xobjects != null)
			{
				XGroup group = new XGroup();
				group.Type = XObjectType.Group;

                List<int> indexes = new List<int>();

				foreach (XObject obj in selection)
				{
                    indexes.Add(xobjects.IndexOf(obj));
				}
                
                indexes.Sort();

                foreach (int i in indexes)
                {
                    group.Children.Add(xobjects[i]);
                }

                foreach (XObject obj in selection)
                {
                    xobjects.Remove(obj);
                }

				xobjects.Add(group);
				selection.Clear();
				selection.Add(group);
			}
		}

		public static void UngroupSelected(List<XObject> xobjects, List<XObject> selection)
		{
			//ungroups the first layer only
			if (selection != null && selection.Count > 0 && xobjects != null)
			{
                List<XGroup> removed = new List<XGroup>();

				foreach (XObject obj in selection)
				{
                    if (obj.Type == XObjectType.Group)
                    {
                        removed.Add((XGroup)obj);
                        int index = xobjects.IndexOf(obj);

                        XGroup group = (XGroup)obj;
                        xobjects.RemoveAt(index);

                        for (int i = 0; i < group.Children.Count; i++)
                        {
                            xobjects.Insert(index + i, group.Children[i]);
                        }
                    }
				}

                foreach (XGroup g in removed)
                {
                    int index = selection.IndexOf(g);
                    for (int i = 0; i < g.Children.Count; i++)
                    {
                        selection.Insert(index + i, g.Children[i]);
                    }

                    selection.Remove(g);
                }
			}
		}

		public static void UngroupAll(List<XObject> xobjects, List<XObject> selection)
		{
			//recursive ungroup
			if (selection != null && selection.Count > 1 && xobjects != null)
			{
				foreach (XObject obj in selection)
				{
					
				}
			}
		}
	}
}
